package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //从redis中获取shopType的列表数据
        String shopTypeList = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_TYPE_LIST);
        List<ShopType> shopTypes = new ArrayList<>();
        //如果列表不为空，则直接返回数据
        if (StrUtil.isNotBlank(shopTypeList)){
            //string字符传转List集合
            shopTypes = JSONObject.parseArray(shopTypeList,ShopType.class);
            shopTypes.stream().sorted(Comparator.comparing(ShopType::getSort)).collect(Collectors.toList());
            return Result.ok(shopTypes);
        }
        shopTypes = query().orderByAsc("sort").list();
        if (shopTypes == null && shopTypes.size() <= 0){
            return Result.fail("店铺类型不存在");
        }
        stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_TYPE_LIST,JSONUtil.toJsonStr(shopTypes),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }
}
